<template>
  <div>
    <a-page-header style="border: 1px solid rgb(235, 237, 240)"
      :title="json.baseinfo.name + '(' + isOnlineStr + ', 更新时间:' + onTime + ')'" @back="onBackClick">
      <template slot="extra">
        <a-button v-has="'user:deviceEdit'" v-show="json.baseinfo.isOnline != 1" type="primary"
          style="margin-right: 10px;" @click="handleConnect">连接</a-button>
        <a-button v-has="'user:deviceEdit'" v-show="json.baseinfo.isOnline == 1" type="danger" style="margin-right: 10px;"
          @click="handleDisconnect">断开</a-button>
      </template>
      <a-row :class="json.baseinfo.isOnline != 1 ? 'disconnect_page' : ''">
        <a-col :span="13">
          <a-card class="ant-card ">
            <div slot="title" class="cardTitle">
              <a-icon type="profile" class="titleIcon on" />
              设备详情
              <a-icon v-has="'user:deviceEdit'" type="setting" class="settingIcon normal" @click="onDetailSettingClick" />
            </div>
            <!--实时数据-->
            <a-row>
              <a-col span="6" class="ant-card-detail-grid">
                <img src="~@/assets/annuoxing/huanxingtu.png" class="card-detail-img">
                <div class="text-overlay">
                  <span class="font-main">{{ json.baseinfo.mainVol*10/10 }}V</span>
                  <span class="font-name">主电电压</span>
                </div>
              </a-col>
              <a-col span="6" class="ant-card-detail-grid">
                <img src="~@/assets/annuoxing/huanxingtu.png" class="card-detail-img">
                <div class="text-overlay">
                  <span class="font-main">{{ json.baseinfo.backVol*10/10 }}V</span>
                  <span class="font-name">备电电压</span>
                </div>
              </a-col>
              <a-col span="6" class="ant-card-detail-grid">
                <img src="~@/assets/annuoxing/huanxingtu.png" class="card-detail-img">
                <div class="text-overlay">
                  <span class="font-main">{{ json.baseinfo.supplyCurrent*10/10 }}A</span>
                  <span class="font-name">供电电流</span>
                </div>
              </a-col>
              <a-col span="6" class="ant-card-detail-grid">
                <img src="~@/assets/annuoxing/huanxingtu.png" class="card-detail-img">
                <div class="text-overlay">
                  <span class="font-main">{{ json.baseinfo.temp*10/10 }}°C</span>
                  <span class="font-name">温度</span>
                </div>
              </a-col>
            </a-row>
            <!--网络信息-->
            <a-row style="margin-top: 10px; ">
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actionipdizhi networkIcon normal" />
                <span class="networkFont">{{ json.network.ip }}</span>
              </a-col>
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actionduankou networkIcon normal" />
                <span class="networkFont">{{ json.network.port }}</span>
              </a-col>
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actionmac networkIcon normal" />
                <span class="networkFont">{{ json.network.mac }}</span>
              </a-col>
            </a-row>
            <a-row style="margin-top: 5px;">
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actionwangguan networkIcon normal" />
                <span class="networkFont">{{ json.network.gateway == '' ? "空" : json.network.gateway }}</span>
              </a-col>
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actiondns networkIcon normal" />
                <span class="networkFont">{{ json.network.dns == '' ? "空" : json.network.dns }}</span>
              </a-col>
              <a-col span="8" class="networkCol">
                <i class="action-jeecg actionmask networkIcon normal" />
                <span class="networkFont">{{ json.network.subnet == '' ? "空" : json.network.subnet }}</span>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <a-col :span="11">
          <a-card class="ant-card" style="height: 312px;">
            <div slot="title" class="cardTitle">
              <a-icon type="alert" class="titleIcon alarm" />
              预警信息
              <a-icon type="setting" v-has="'user:deviceEdit'" class="settingIcon normal" @click="onWarnConfigClick" />
            </div>
            <a-row>
              <a-col span="8">
                <span
                  :class="json.warning.mainVol == 0 ? 'action-jeecg actiondianyabiao statusSettingIcon on' : 'action-jeecg actiondianyabiao statusSettingIcon err'">
                  <span class="statusFont">主电压异常</span>
                </span>
              </a-col>
              <a-col span="8">
                <span
                  :class="json.warning.backVol == 0 ? 'action-jeecg actiondianya statusSettingIcon on' : 'action-jeecg actiondianya statusSettingIcon err'">
                  <span class="statusFont">备电压异常</span>
                </span>
              </a-col>
              <a-col span="8">
                <span
                  :class="json.warning.current == 0 ? 'action-jeecg actiondianliu statusSettingIcon on' : 'action-jeecg actiondianliu statusSettingIcon err'">
                  <span class="statusFont">总电流异常</span>
                </span>
              </a-col>
            </a-row>
            <a-row>
              <a-col span="8">
                <span
                  :class="json.warning.temp == 0 ? 'action-jeecg actionwendu1 statusSettingIcon on' : 'action-jeecg actionwendu1 statusSettingIcon err'">
                  <span class="statusFont">温度异常</span>
                </span>
              </a-col>
              <a-col span="8">
                <span
                  :class="json.warning.ups == 0 ? 'action-jeecg actionyujingups statusSettingIcon on' : 'action-jeecg actionyujingups statusSettingIcon err'">
                  <span class="statusFont">UPS异常</span>
                </span>
              </a-col>
              <a-col span="8">
                <span
                  :class="json.warning.cityVol == 0 ? 'action-jeecg actionyujingshidian statusSettingIcon on' : 'action-jeecg actionyujingshidian statusSettingIcon err'">
                  <span class="statusFont">市电异常</span>
                </span>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
      <a-row :class="json.baseinfo.isOnline != 1 ? 'disconnect_page' : ''">
        <a-col :span=24>
          <a-card class="ant-card">
            <div slot="title" class="cardTitle">
              <a-icon type="control" class="titleIcon on" />
              开关信息
              <a-icon type="setting" v-has="'user:deviceEdit'" class="settingIcon normal"
                @click="onChannelSettingClick" />
            </div>
            <!--开关展示-->
            <a-row v-for="(row, rowIndex) in switchesChunks" :key="rowIndex">
              <div v-for="(item, index) in row">
                <a-col :span="3" v-bind:key="(rowIndex - 1) * colSwitchesCount + index + '_#switch'">
                  <div class="switchCard">
                    <div slot="title" class="switch-card-title">
                      {{ item.name==undefined||item.name==""?"通道"+(rowIndex * colSwitchesCount + index + 1):item.name.slice(0,18) }}
                    </div>
                    <a-row style="margin-bottom: 5px;">
                      <a-col span="4" class="action-jeecg actiondianliu1 on switch-card-item-icon" />
                      <a-col span="10" class="switch-card-item-font">{{ item.current*10/10 }}</a-col>
                      <a-col span="5" v-if="item.iswarning == 1"
                        class="action-jeecg actiondevicewarn err switch-card-item-warn" />
                        <a-col span="50">
                          <span
                        :class="item.state == 0 ? 'action-jeecg actiondeviceon open switchLightIcon' : 'action-jeecg actiondeviceoff off switchLightIcon'"></span>
                        </a-col>    
                    </a-row> 
                  </div>
                </a-col>
              </div>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
    </a-page-header>
    <!-- <a-button @click="onShowShadowDetailClick">显示/隐藏设备数据结构</a-button>
    <a-row v-show="showDetail">
      <a-col :span="24">
        <vue-json-editor v-model="json" :show-btns="true" :expandedOnStart="true"
          @json-save="onJsonSave"></vue-json-editor>
      </a-col>
    </a-row> -->
    <TigDeviceChannelSettingModal ref="tigDeviceChannelSettingModal"></TigDeviceChannelSettingModal>
    <TigDeviceConfigSetModal ref="tigDeviceConfigSetModal"></TigDeviceConfigSetModal>
    <tig-device-modal ref="modalForm" @ok="modalFormOk"></tig-device-modal>
  </div>
</template>


<script>

import { getDeviceinfo } from '@/api/deviceApi'
import store from '@/store/'
import vueJsonEditor from 'vue-json-editor'
import { connectDevice, disConnectDevice } from '@/api/deviceApi'
import { formatDate } from '@/utils/util'
import TigDeviceChannelSettingModal from './popups/TigDeviceChannelSettingModal'

import TigDeviceConfigSetModal from './popups/TigDeviceConfigSetModal'
import TigDeviceModal from './TigDeviceModal'

export default {
  name: 'TigDeviceSetting',
  //inject: ['closeCurrent'],
  components: {
    vueJsonEditor,
    TigDeviceChannelSettingModal,
    TigDeviceConfigSetModal,
    TigDeviceModal
  },
  props: {

  },
  data() {
    return {
      model: {},

      checked: false,
      json: {
        baseinfo: {},
        network: {},
        warning: {},
        switches: {
          total: 0,
          switches: []
        }
      },
      record: {
        shadow: {
          baseinfo: {},
          network: {},
          warning: {},
          switches: {
            total: 0,
            switches: []
          }
        }
      },
      lockReconnect: false,
      deviceId: '',
      showDetail: false,
      colSwitchesCount: 8,
    }
  },
  computed: {
    isOnline() {//computed需要监听data中的属性才能刷新页面
      return this.json.baseinfo.isOnline
    },
    isOnTime() {//computed需要监听data中的属性才能刷新页面
      return this.json.onTime
    },
    isOffTime() {//computed需要监听data中的属性才能刷新页面
      return this.json.offTime
    },
    isOnlineStr: function () {
      return this.json.baseinfo.isOnline == '1' ? '在线' : '离线';
    },
    onTime: function () {
      if (this.json.onTime)
        return formatDate(this.json.onTime, 'yyyy-MM-dd hh:mm:ss')
    },
    offTime: function () {
      if (this.json.offTime)
        return formatDate(this.json.offTime, 'yyyy-MM-dd hh:mm:ss')
    },
    // input: function () {
    //   if (this.json.baseinfo.input == '0')
    //     return '主'
    //   if (this.json.baseinfo.input == '1')
    //     return '备'
    //   if (this.json.baseinfo.input == '2')
    //     return '双'
    // },
    // output: function () {
    //   if (this.json.baseinfo.output == '0')
    //     return '主'
    //   if (this.json.baseinfo.output == '1')
    //     return '备'
    // },
    // wanringList: function () {
    //   return [{ name: '市电异常', value: this.json.warning.cityVol }, { name: '主电异常', value: this.json.warning.mainVol },
    //   { name: '总电流异常', value: this.json.warning.current }, { name: 'UPS异常', value: this.json.warning.ups },
    //   { name: '备电压异常', value: this.json.warning.backVol }, { name: '温度异常', value: this.json.warning.temp }]
    // },
    switchesChunks() {
      const chunks = [];
      for (let i = 0; i < this.json.switches.total; i += this.colSwitchesCount) {
        chunks.push(this.json.switches.switches.slice(i, i + this.colSwitchesCount));
      }
      return chunks;
    },
  },
  created() {
    this.deviceId = this.$route.query.deviceId;
    this.loadData()
  },
  mounted() {
    this.initWebSocket();

  },
  methods: {
    view(record) {
      //this.model = record
    },
    loadData() {
      var _that = this
      getDeviceinfo({ deviceId: this.deviceId }).then((res) => {
        if (res.success) {
          let data = JSON.parse(res.message)
          if (data.shadow != null) {
            _that.json = data.shadow;
            _that.record = data;
          }
          else {
            _that.json = data;
          }
        }
       // console.log("------TigDeviceSetting:getDeviceinfo" + JSON.stringify(_that.json));
      })
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id;
      var url = window._CONFIG['WS_URL'] + "/deviceWebsocket/" + this.deviceId;
      // var url = window._CONFIG['WS_URL'] + "/deviceWebsocket/"+this.deviceId;
      //console.log("svalue", url)
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      console.log("设备WebSocket连接成功");
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log("设备WebSocket连接发生错误");
      this.reconnect();
    },
    websocketOnmessage: function (e) {
      var data = eval("(" + e.data + ")"); //解析对象
      if (data.shadow != null) {
        this.json = data.shadow;
        this.record = data;
      }
      else {
        this.json = data;
      }
      //console.log("------TigDeviceSetting:websocketOnmessage" + JSON.stringify(this.json));
      // if(this.json.baseinfo.isOnline == 0){
      //   console.log('webSocketMsg isOnline == 0')
      // }
      //console.log('webSocketMsg：' + JSON.stringify(data))
      if (data.cmd) {
        if (data.cmd == 'ACK') {
          if (data.cmdStr == "" || data.cmdStr == undefined) {
            //this.$message.info("指令成功下发")
          } else {
            //this.$message.info("指令下发失败")
          }
        }
      }
    },
    websocketOnclose: function (e) {
      console.log("connection closed (" + e + ")");
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) { // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    onJsonSave() {

    },
    handleConnect() {
      connectDevice({ deviceId: this.deviceId, manualConnect: true }).then(res => {
        this.$message.info("连接已发送")
      });
    },
    handleDisconnect() {
      disConnectDevice({ deviceId: this.deviceId, manualDisconnect: true }).then(res => {
        this.$message.info("请求已发送")
      });
    },
    isWarning(num) {
      if (num == 1) return 'color:red'
      else return 'color:gray'
    },
    onShowShadowDetailClick() {
      this.showDetail = !this.showDetail
    },
    onChannelSettingClick() {
      this.$refs.tigDeviceChannelSettingModal.edit(this.json)
    },
    onWarnConfigClick() {
      this.$refs.tigDeviceConfigSetModal.edit(this.json)
    },
    onBackClick() {
      //this.closeCurrent();
      this.$router.go(-1);
    },
    onDetailSettingClick() {
      this.$refs.modalForm.edit(this.record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    modalFormOk() {
      // 重新加载页面
      this.loadData();
    },
  }
}
</script>

<style lang="less" scoped>
table {
  font-size: 15px;
  width: 100%;
}

th,
td {
  padding: 2px;
  border: 1px solid black;
}

.on {
  color: #0aabf6 !important;
}

.disconnect_page {
  filter: progid:DXImageTransform.Microsoft.BasicImage(graysale=1);
  -webkit-filter: grayscale(100%);
}

.off {
  color: #b3b4c5 !important;
}

.alarm {
  color: rgba(241, 157, 83, 0.832);
}

.err {
  color: red !important;
}

.normal {
  color: rgb(101, 95, 95);
}

.off {
  color: rgb(101, 95, 95);
}

.open {
  color: rgb(13, 157, 10);
}

.cardTitle {
  display: flex;
  align-content: center;
  flex-direction: row;
}

.titleIcon {
  padding-right: 10px;
  font-size: 28px;
}

.settingIcon {
  padding-right: 10px;
  font-size: 20px;
  position: absolute;
  right: 0;
}

.switchLightIcon {
  font-size: 24px;
  font-weight: 400;
  position: absolute;
  right: 0;
}

.statusCol {
  // display: flex;
  // flex-direction: column;
}

.statusSettingIcon {
  // font-size: 56px;
  // font-weight: 500;
  // vertical-align: top;
  // display: flex;
  // align-content: center;
  // justify-content: center;

  font-size: 56px;
  font-weight: 500;
  text-align: center;
  display: flex;
  flex-direction: column;
}

.statusFont {
  font-size: 12px;
  font-weight: 600;
  color: rgb(83, 86, 86);
}

.networkIcon {
  font-size: 28px;
  font-weight: 500;
  vertical-align: top;
  display: flex;
  align-content: center;
  justify-content: left;
}

.networkCol {
  padding-top: 3px;
  padding-left: 12px;
  display: flex;
  justify-content: left;
  flex-direction: row;
  vertical-align: bottom;
  align-items: center;
  justify-items: center;
}

.networkFont {
  font-size: 12px;
  font-weight: 600;
  vertical-align: bottom;
  text-align: bottom;
  padding-left: 8px;
}


.ant-card {
  margin-top: 10px;
  margin-right: 10px;
  border-radius: 20px;
}

.ant-card-detail-grid {
  position: relative;
  border-color: white;

  .card-detail-img {
    display: block;
    margin: 0 auto;
    height: 100px;
    width: 100px;
  }

  .font-main {
    font-size: 19px;
    font-weight: 600;
    color: rgb(28, 144, 245);
    text-align: center;
  }

  .font-name {
    font-size: 12px;
    font-weight: 500;
    color: rgb(7, 8, 8);
    text-align: center;
  }

  .warning-item {
    display: flex;
    justify-content: center;
    align-content: center
  }
}

.switchCard {
  position: relative;
  border: 1px solid #7074763b;
  box-shadow: 3px 3px 6px rgb(219, 207, 207);
  font-size: 18px;
  line-height: 18px;
  display: block;
  height: 70px;
  width: 95%;
  padding: 5px 5px;
  margin-bottom: 10px;
  border-radius: 8px;
  cursor: pointer;
}

.switch-card-title {
  display: flex;
  align-content: center;
  flex-direction: row;
  font-size: 10px;
  font-weight: 550;
  margin-bottom: 5px;
  /**超出单行用省略号 */
  // overflow: hidden;
  overflow-wrap: break-word;
  height: 38px;
  //text-overflow: ellipsis;
  // white-space: nowrap
    /**-------------------------- */
}

.switch-card-item-font {
  display: flex;
  align-content: center;
  flex-direction: row;
  font-size: 13px;
  font-weight: 500;
  padding-left: 5px;
}

.switch-card-item-icon {
  font-size: 17px;
  display: flex;
  align-content: center;
  vertical-align: top;
  justify-content: left;
}

.switch-card-item-warn {
  font-size: 17px;
  display: flex;
  align-content: center;
  vertical-align: bottom;
  justify-content: right;
}

.text-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transform: translate(-50%, -50%);
}

.ant-card-bordered {
  border: 0px;
}
</style>